package com.m1book.site;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.m1book.domain.book.ABook;
import com.m1book.domain.relation.InviteTrace;
import com.m1book.domain.user.Miser;
import com.m1book.repositories.user.MiserRepository;

@RequestMapping("/miser")
@Controller
@SessionAttributes("inviteTrace")
public class MisershowController {
	private static final Logger logger = LoggerFactory.getLogger(MisershowController.class);
	
	@Autowired
	private MiserRepository miserRepository;
	
	@RequestMapping(value = "/show/{miserId}", method = RequestMethod.GET)
	public String show(@PathVariable String miserId, Model model, HttpSession session) {
		ObjectId id = new ObjectId(miserId);
		Miser miser = miserRepository.findOne(id);
		if (miser == null) {
			model.addAttribute("resource", miserId);
			return "commonfailed";
		}
		
		InviteTrace inviteTrace = (InviteTrace) session.getAttribute("inviteTrace");
		if(inviteTrace != null) {
			// 如果是因为被邀请进入Miser秀场，则显示真名。
			logger.info("visit miser show by " + inviteTrace.toString());
			model.addAttribute("misername", miser.getInfo().getRealname());
		} else {
			// 否则显示昵称
			model.addAttribute("misername", miser.getInfo().getNickname());
		}
		
		List<ABook> abooks = miser.getDonatABooks();
		model.addAttribute("abooks", abooks);
		
		return "/miser/show";
	}

}
